package com.pacifico.telebusca.web.controladores;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.displaytag.tags.TableTagParameters;
import org.displaytag.util.ParamEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pacifico.telebusca.dominio.Audio;
import com.pacifico.telebusca.dominio.Empresa;
import com.pacifico.telebusca.exception.Errores;
import com.pacifico.telebusca.web.facade.TeleBuscaFacade;
import com.pacifico.telebusca.web.util.Util;

@Controller
public class ControladorConsultarAudio {

	private static final int BUFFER_SIZE = 4096;
	private static final String PAGE_PARAM = new ParamEncoder("result").encodeParameterName(TableTagParameters.PARAMETER_PAGE);
	
	@Value("#{telebusca['maximofilas']}")
	private String maxNumber;
	
	@Value("#{telebusca['rangodias']}")
	private String rangodias;
	
	
	

	@Autowired
	private TeleBuscaFacade teleBuscaFacade;
	

	@RequestMapping(value = "/descargarAudio", method = RequestMethod.GET)
	public String descargarAudio(HttpServletRequest request,
			HttpServletResponse response, Model map,
			@RequestParam int codEmpresa, @RequestParam String path,
			@ModelAttribute Audio audio) throws IOException {

		try {
			List<Empresa> empresas = this.teleBuscaFacade
					.listarUsuariosyEmpresasByNombreUsuario(Util
							.obtenerNombreUsuario(SecurityContextHolder
									.getContext()));
			Empresa empresa = this.teleBuscaFacade
			.buscarEmpresaPorCodigo(codEmpresa);
			map.addAttribute("rangodias", rangodias);
			map.addAttribute("empresas", empresas);

			map.addAttribute("audio", audio);
			String urlAudio = empresa.getCarpeta()+ path;			
			File downloadFile = null;
			downloadFile = teleBuscaFacade.descargarAudio(urlAudio);

			FileInputStream inputStream = new FileInputStream(downloadFile);
			String mimeType = "application/octet-stream";			
			response.setContentType(mimeType);
			response.setContentLength((int) downloadFile.length());
			String headerKey = "Content-Disposition";
			String headerValue = String.format("attachment; filename=\"%s\"",
					downloadFile.getName());
			response.setHeader(headerKey, headerValue);

			OutputStream outStream = response.getOutputStream();

			byte[] buffer = new byte[BUFFER_SIZE];
			int bytesRead = -1;

			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, bytesRead);
			}

			inputStream.close();
			outStream.close();
			teleBuscaFacade.registrarAuditoria("T0013", "T0014");			
		} catch (Exception e) {
			e.printStackTrace();
			if (e.getCause()!=null){
				if (e.getCause().getCause()!=null){
					if(!e.getCause().getCause().getMessage().equals("")){
						if(e.getCause().getCause().getMessage().contains("Cannot release connection")){
							map.addAttribute("error", Errores.MAP.get("E0002"));				
							return "consultaraudios";
						}
					}
				}	
			}
			
			
			
			map.addAttribute("error", Errores.MAP.get("E4001"));
			teleBuscaFacade.registrarAuditoria("T0013", "T0015");
			//map.addAttribute("mensaje", Errores.MAP.get("E4001"));
			return "consultaraudios";
		}
		return "consultaraudios";

	}
	
	
	
	@RequestMapping(value = "/numerodias", method = RequestMethod.POST)
	public @ResponseBody String numeroDias(HttpServletRequest request,
			HttpServletResponse response,Model map){				
		return rangodias;
	}
	
	
	@RequestMapping(value = "/escuchar", method = RequestMethod.POST)
	public @ResponseBody String url(HttpServletRequest request,
			HttpServletResponse response,@RequestParam String path,@RequestParam String codEmpresa,Model map){
		String urlAudio = "";
		try {			
			
			map.addAttribute("rangodias", rangodias);
			Empresa empresa = this.teleBuscaFacade
					.buscarEmpresaPorCodigo(Integer.parseInt(codEmpresa));
			
			String urlAudioAux = empresa.getCarpeta()+ path;			
			/*File downloadFile = null;			
			downloadFile = teleBuscaFacade.descargarAudio(urlAudioAux);
			FileInputStream inputStream = new FileInputStream(downloadFile);*/
			urlAudio = "https://" +request.getServerName() + ":"+request.getServerPort()+ request.getContextPath() + "/resources/audios"
					+ empresa.getCarpeta() + "" + path;
									
			teleBuscaFacade.registrarAuditoria("T0016","T0017");
			
		} catch (Exception e) {
			e.printStackTrace();
			//map.addAttribute("error", e.getMessage());
			teleBuscaFacade.registrarAuditoria("T0016","T0018");		
			
			if (e.getCause()!=null){
				if (e.getCause().getCause()!=null){
					if(!e.getCause().getCause().getMessage().equals("")){
						if(e.getCause().getCause().getMessage().contains("Cannot release connection")){
							map.addAttribute("error", Errores.MAP.get("E0002"));				
							return "consultaraudios";
						}
					}
				}	
			}
			map.addAttribute("error", Errores.MAP.get("E5001"));
			return "consultaraudios";
		}
		
		return urlAudio;
	}

	

	
	@RequestMapping(value = "/buscaraudios", method = RequestMethod.GET)
	public String buscarAudios(HttpServletRequest request,
			HttpServletResponse response, Model map, @ModelAttribute Audio audio) {
		List<Audio> listaaudios = null;

		try {
			Integer firstResult = null;
			Integer numberoPagina = null;
			String numberoPaginas = request.getParameter(PAGE_PARAM);
			
			List cadena = new ArrayList();
			
			List<Empresa> empresas = teleBuscaFacade
					.listarUsuariosyEmpresasByNombreUsuario(Util
							.obtenerNombreUsuario(SecurityContextHolder
									.getContext()));
			
			for (Iterator iterator = empresas.iterator(); iterator.hasNext();) {
				Empresa empresa = (Empresa) iterator.next();
				cadena.add(empresa.getCodEmpresa());
			} 
			
			
			
			System.out.println("cadena = " + cadena.size());
			audio.setCadena(cadena);
			
			int total = teleBuscaFacade.buscarContarAudios(audio);
			if (numberoPaginas != null){
				numberoPagina = Integer.valueOf(numberoPaginas);
				firstResult = (numberoPagina - 1) * Integer.valueOf(maxNumber);	
			}
			
			
			
			
			
			if (firstResult == null){				
				listaaudios = teleBuscaFacade.buscarAudios(audio, 0, total);
			} else {
				listaaudios = teleBuscaFacade.buscarAudios(audio, firstResult, Integer.valueOf(maxNumber));
			}
			System.out.println("maxNumber " + maxNumber);
			map.addAttribute("maxNumber", Integer.valueOf(maxNumber));
			map.addAttribute("listaaudios", listaaudios);
			map.addAttribute("rangodias", rangodias);
			
			map.addAttribute("empresas", empresas);
			map.addAttribute("empresasnombres", teleBuscaFacade.listarEmpresas());
			

			map.addAttribute("audio", audio);
			teleBuscaFacade.registrarAuditoria("T0019","T0020");
			if (listaaudios == null || listaaudios.isEmpty()){
				map.addAttribute("mensaje", Errores.MAP.get("E3001"));
			}
			

		} catch (Exception e) {
			e.printStackTrace();
			if(e.getCause().getCause().getMessage().contains("Cannot release connection")){
				map.addAttribute("error", Errores.MAP.get("E0002"));				
				return "consultaraudios";
			}
			map.addAttribute("mensaje", Errores.MAP.get("T0021"));
			teleBuscaFacade.registrarAuditoria("T0019","T0021");
			return "consultaraudios";
		}
		return "consultaraudios";

	}
}
